package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Date;

public class JWTUtil {
    private static Long expire = 1000L * 60 * 60 * 24 * 365;

    private static Key key = Keys.hmacShaKeyFor("VP8ZQBfj0q2SRXAmBMYIbCbL9znlKNTc".getBytes());

    public static String createToken(Long userId, String username) {

        return Jwts.builder()    //Jwts.builder().compact()  创建token
                .setExpiration(new Date(System.currentTimeMillis() + expire))//设置token过期时间
                .setSubject("lease_systemOrApp_user")//设置主题
                .claim("userId", userId)//设置token保存信息
                .claim("username", username)
                .signWith(key)//设置签名(防伪标识)
                .compact();
    }
    public static Claims parseToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(key).
                    build().parseClaimsJws(token);//根据签名解析token
            return claimsJws.getBody();
        } catch (ExpiredJwtException e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_EXPIRED);//过期
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);//非法
        }
    }
}
